<?php
/**
 * Created by PhpStorm.
 * FileName: CronController.php
 * User: Administrator
 * Date: 2018/2/27
 * Time: 10:29
 */

namespace Admin\Controller;

use Admin\Model\MoneyModel;
use Admin\Model\OrderStatusHistoryModel;
use Admin\Model\TripModel;
use Admin\Model\UserModel;
use Think\Controller;

/**
 * 定时任务控制器
 * Class CronController
 * @package Admin\Controller
 */
class CronController extends Controller {

    private $tripModel;
    private $userModel;
    private $moneyModel;
    private $orderStatusHistoryModel;

    function __construct() {
        $this->tripModel = new TripModel();
        $this->userModel = new UserModel();
        $this->moneyModel = new MoneyModel();
        $this->orderStatusHistoryModel = new OrderStatusHistoryModel();
    }

    // 处理已到期的行程
    public function handleExpiredTrip() {
        // 将已到期的行程，且当前状态为 【1 接单中 | 2 订单已满 | 4 已暂停接单】，修改为 【3 接单结束】
        $sql = 'update trip t,';
        $sql .= '(select trip_id from (select trip_id,max(reach_date) as reach_date from airway group by trip_id) a where UNIX_TIMESTAMP()> a.reach_date) a ';
        $sql .= 'set t.state=3 ';
        $sql .= 'where t.id=a.trip_id and t.state in (1,2,4)';
        M()->execute($sql);
    }

    // 处理已到期的订单
    public function handleExpiredOrder() {
        $sql = 'select id,deposit,reward,buyer_id,order_no from `order` o where o.state=0 and exists (select 1 from trip t where o.trip_id=t.id and UNIX_TIMESTAMP() > t.reach_date)';
        $orderList = M()->query($sql);
        foreach ($orderList as $order) {
            // 取消订单
            $sql = 'update `order` set state=5 where id='.$order['id'];
            M()->execute($sql);
            // 订单付款处理
            $this->handleOrderAmount($order);
            // 添加订单状态变更记录
            $this->addOrderStatusHistory($order);
        }
    }

    // 订单付款处理
    private function handleOrderAmount($order) {
        // 订单取消后，将预付款（保证金）和赏金退还给客户
        $money = $order['deposit']+$order['reward'];
        $this->userModel->where(array('id' => $order['buyer_id']))->setInc('money',$money);
        // 资金流水处理
        $msg = '订单取消，退款至客户，订单编号：'.$order['order_no'];
        $this->handleCapitalFlow($order['buyer_id'],$money,3,$msg);
    }

    // 资金流水处理
    private function handleCapitalFlow ($userId,$money=0,$type=0,$remark='') {
        $moneyData = array(
            'user_id' => $userId,
            'money' => $money,
            'type' => $type,
            'remark' => $remark
        );
        $this->moneyModel->add($moneyData);
    }

    // 添加订单状态变更记录
    private function addOrderStatusHistory($order) {
        $data = array(
            'order_id' => $order['id'],
            'user_id' => 1,
            'status' => 5,
            'remark' => '系统自动取消订单'
        );
        $this->orderStatusHistoryModel->add($data);
    }

}